package com.jn.exam.question.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jn.exam.*;
import com.jn.exam.question.entity.PersonalQuestion;
import com.jn.exam.question.entity.PersonalQuestionStore;
import com.jn.exam.question.entity.Question;
import com.jn.exam.question.entity.vo.QuestionWrapper;
import com.jn.exam.question.service.OssFeignService;
import com.jn.exam.question.service.PersonalQuestionService;
import com.jn.exam.question.service.PersonalQuestionStoreService;
import com.jn.exam.question.service.QuestionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.Future;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 江南大学1033190417
 * @since 2022-01-18
 */
@RestController
@RequestMapping("/question/personal-question-store")
@Api(description = "个性化题库")
public class PersonalQuestionStoreController {

    @Autowired
    private PersonalQuestionStoreService personalQuestionStoreService;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private PersonalQuestionService personalQuestionService;


    /**
     * @param request               servlet请求
     * @param personalQuestionStore 题库
     * @return R
     */
    @ApiOperation(value = "创建题库")
    @PostMapping("createPersonalQuestionStore")
    public R createPersonalQuestionStore(HttpServletRequest request, @RequestBody PersonalQuestionStore personalQuestionStore) {
        String id = JwtUtils.getMemberIdByJwtToken(request);
        personalQuestionStore.setTeacherId(id);
        boolean save = personalQuestionStoreService.save(personalQuestionStore);
        if (save) {
            return R.ok().message("创建成功");
        } else {
            return R.error().message("创建失败");
        }

    }


    @ApiOperation(value = "更新题库信息")
    @PostMapping("updatePersonalQuestionStore")
    public R updatePersonalQuestionStore(@RequestBody PersonalQuestionStore personalQuestionStore) {
        boolean update = personalQuestionStoreService.updateById(personalQuestionStore);
        if (update) {
            return R.ok().message("更新成功");
        }
        return R.error().message("更新失败");
    }


    @ApiOperation(value = "根据教师id展示所有题库")
    @GetMapping("getAllPersonalQuestionStore")
    public R getAllPersonalQuestionStore(HttpServletRequest request) {
        String teacherId = JwtUtils.getMemberIdByJwtToken(request);
        QueryWrapper<PersonalQuestionStore> wrapper = new QueryWrapper<>();
        wrapper.eq("teacher_id", teacherId);
        wrapper.orderByDesc("gmt_create");
        List<PersonalQuestionStore> personalQuestionStores = personalQuestionStoreService.list(wrapper);
        return R.ok().data("personalQuestionStores", personalQuestionStores);
    }

    /**
     * @param personalQuestionStoreId 题库id
     * @return R
     */
    @ApiOperation(value = "删除题库，谨慎操作，连带题库中的题都将永久删除")
    @PostMapping("deletePersonalQuestionStore/{personalQuestionStoreId}")
    @Transactional
    public R deletePersonalQuestionStore(@PathVariable("personalQuestionStoreId") String personalQuestionStoreId) {
        boolean b = personalQuestionService.removeQuestionByPersonalQuestionStoreId(personalQuestionStoreId);
        if (b) {
            return R.ok().message("删除成功");
        }
        return R.error().message("删除失败");
    }

    /**
     * @param questionIds              总题库试题id组
     * @param personalQuestionStoreIds 老师个人题库id组
     * @return R
     */
    @ApiOperation(value = "往已创建题库添加总题库试题")
    @PostMapping("addQuestionToPersonalStore")
    @Transactional(rollbackFor = Exception.class)
    public R addQuestionToPersonalStore(String[] questionIds,
                                        String[] personalQuestionStoreIds) throws Exception {
        List<Future<Boolean>> futures = new ArrayList<>();
        for (String questionId : questionIds) {
            Question question = questionService.getById(questionId);
            for (String personalQuestionStoreId : personalQuestionStoreIds) {
                Question clone = CloneUtils.clone(question);
                Future<Boolean> isOK = personalQuestionStoreService.addQuestionToPersonalStore(clone, personalQuestionStoreId);
                futures.add(isOK);
            }
        }
        for (Future<Boolean> future : futures) {
            Boolean isOK = future.get();
            if (!isOK) {
                return R.ok().message("添加失败");
            }
        }
        return R.ok().message("添加成功");
    }

    @ApiOperation("根据id查单条")
    @GetMapping("getPersonalQuestionById/{personalQuestionId}")
    public R getPersonalQuestionById(@PathVariable("personalQuestionId") String personalQuestionId) {
        PersonalQuestion personalQuestion = personalQuestionService.getById(personalQuestionId);
        return R.ok().data("personalQuestion", personalQuestion);
    }

    @ApiOperation(value = "查询老师某个题库中每种题型的数量")
    @GetMapping("getPersonalQuestionStoreTypeNumber/{personalQuestionStoreId}")
    public R getPersonalQuestionStoreTypeNumber(@PathVariable("personalQuestionStoreId") String personalQuestionStoreId) {
        List<Map<String, Integer>> typeMap = personalQuestionStoreService.getPersonalQuestionStoreTypeNumber(personalQuestionStoreId);
        return R.ok().data("type", typeMap);
    }


    @ApiOperation("添加试题到个性化题库")
    @PostMapping("addQuestionToPersonalQuestionStore")
    @Transactional(rollbackFor = Exception.class)
    public R addQuestionToPersonalQuestionStore(@RequestBody PersonalQuestion personalQuestion, String[] personalQuestionStoreIds) {
        for (String personalQuestionStoreId : personalQuestionStoreIds) {
            personalQuestion.setStoreId(personalQuestionStoreId);
            boolean save = personalQuestionService.save(personalQuestion);
            if (!save) {
                return R.error().message("添加失败");
            }
        }
        return R.ok().message("添加成功");
    }

    @ApiOperation(value = "更新某个性化题库试题")
    @PostMapping("updatePersonalQuestion")
    public R updatePersonalQuestion(@RequestBody PersonalQuestion personalQuestion) {
        boolean isUpdate = personalQuestionService.updateById(personalQuestion);
        if (isUpdate) {
            return R.ok().message("更新成功");
        }
        return R.error().message("更新失败");
    }


    //模糊分页查询
    @ApiOperation(value = "模糊分页查询")
    @PostMapping("pagePersonalQuestionCondition")
    public R pagePersonalQuestionCondition(
            @RequestBody QuestionWrapper questionWrapper) {
        Integer total = personalQuestionStoreService.pageTotal(questionWrapper);
        if (total == 0) {
            return R.ok().data("rows", null).data("total", total);
        }
        long current = questionWrapper.getCurrent();
        long limit = questionWrapper.getLimit();
        questionWrapper.setCurrent(current * limit);
//        if (current * limit + limit - 1 > total) {
//            questionWrapper.setLimit(total - 1);
//        }
        List<PersonalQuestion> questions = personalQuestionStoreService.pageSelect(questionWrapper);
        if (questions != null) {
            return R.ok().data("rows", questions).data("total", total);
        }
        return R.error().message("查询失败");
    }

    @ApiOperation("逻辑删除多个个人题目")
    @PostMapping("deletePersonalQuestionByIdsLogic")
    @Transactional
    public R deletePersonalQuestionByIdsLogic(String[] personalQuestionIds) {
        boolean removeByIds = personalQuestionService.removeByIds(personalQuestionIds);
        if (removeByIds) {
            return R.ok().message("删除成功");
        }
        return R.error().message("删除失败");
    }

    @ApiOperation("彻底删除多个个人试题")
    @PostMapping("deletePersonalQuestionBysIdComplete")
    @Transactional
    public R deletePersonalQuestionBysIdComplete(String[] personalQuestionIds) throws Exception {
        List<Future<Boolean>> futures = new ArrayList<>();
        for (String personalQuestionId : personalQuestionIds) {
            Future<Boolean> future = personalQuestionService.deletePersonalQuestionByIdComplete(personalQuestionId);
            futures.add(future);
        }
        for (Future<Boolean> future : futures) {
            Boolean b = future.get();
            if (!b) {
                return R.error().message("删除失败");
            }
        }
        return R.ok().message("删除成功");
    }

    @ApiOperation("查询某题库中已删除")
    @GetMapping("getPersonalQuestionHasDeleted/{personalQuestionStoreId}")
    public R getPersonalQuestionHasDeleted(@PathVariable("personalQuestionStoreId") String personalQuestionStoreId) {
        List<PersonalQuestion> personalQuestions = personalQuestionService.getPersonalQuestionHasDeleted(personalQuestionStoreId);
        if (personalQuestions != null) {
            for (PersonalQuestion question : personalQuestions) {
                Date d1 = question.getGmtModified();
                d1 = DateTimeUtil.addDays(d1, 31);
                Date d2 = new Date();
                int daysBetweenTwoDate = DateTimeUtil.daysBetweenTwoDate(d2, d1);
                question.setRemainingDays(daysBetweenTwoDate);
            }
            return R.ok().data("personalQuestions", personalQuestions);
        }
        return R.error().message("查询失败");
    }

    @ApiOperation("恢复已删除试题")
    @PostMapping("recoveryDeleted")
    public R recoveryDeleted(String[] personalQuestionIds) {
        boolean isRecovery = personalQuestionService.recoveryDeleted(personalQuestionIds);
        if (isRecovery) {
            return R.ok().message("恢复成功");
        }
        return R.error().message("恢复失败");
    }

}

